import 'package:flower/pages/tabs/home/home_page.dart';
import 'package:flower/pages/tabs/shoppingcart/cart_page.dart';
import 'package:flower/pages/tabs/user/user_page.dart';
import 'package:flower/utils/my_colors.dart';
import 'package:flutter/material.dart';
import "package:flower/utils/my_icons.dart";


class IndexPage extends StatefulWidget {
  final int initialIndex;

  const IndexPage({Key? key, this.initialIndex = 0}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return IndexPageState();
  }
}

class IndexPageState extends State<IndexPage> {
  late int currentIndex;
  late PageController controller;

  @override
  void initState() {
    super.initState();
    currentIndex = widget.initialIndex;
    controller = PageController(initialPage: currentIndex);
  }

  List<Widget> pageList = [const HomePage(), const Cart(), const UserPage()];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: controller,
        physics: const NeverScrollableScrollPhysics(),
        onPageChanged: (index) {
          setState(() {
            currentIndex = index;
          });
        },
        children: pageList,
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const [
          BottomNavigationBarItem(icon: Icon(MyIcons.home), label: '主页'),
          BottomNavigationBarItem(icon: Icon(MyIcons.cart), label: '购物车'),
          BottomNavigationBarItem(icon: Icon(MyIcons.personal), label: '我的')
        ],
        currentIndex: currentIndex,
        type: BottomNavigationBarType.fixed,
        selectedItemColor: MyColors.boyPink, // 设置选中时的颜色
        onTap: (index) {
          jump(index);
        },
      ),
    );
  }

  void jump(index) async {
    //当进入购物车和用户中心页面时先判断登录状态
    // if (index == 2 || index == 3) {
    //   if (!await UserService.isLogin()) {
    //     Fluttertoast.showToast(msg: "请先登录");
    //     //打开登录页面
    //     Navigator.pushNamed(context, '/login'); //使用命名路由跳转
    //     return;
    //   }
    // }
    setState(() {
      controller.jumpToPage(index);
      currentIndex = index;
    });
  }
}
